package cn.easy.mortgage.service;

import cn.easy.base.bean.PageBean;
import cn.easy.base.service.BaseService;
import cn.easy.base.utils.BaseUtils;
import cn.easy.base.utils.jdbc.PaginationHelper;
import cn.easy.mortgage.domain.Channel;
import cn.easy.mortgage.domain.LoanRequest;
import cn.easy.mortgage.repository.LoanRequestDao;
import cn.easy.mortgage.utils.Constants;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static cn.easy.base.utils.SpringSecurityUtils.getCurrentUserId;
import static cn.easy.base.utils.SpringSecurityUtils.hasPermission;

@Component
public class LoanRequestService extends BaseService<LoanRequest> {
    @Autowired
    private LoanRequestDao loanRequestDao;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Page<LoanRequest> search(Map<String, Object> searchParams, PageBean pageBean) {
        List<Object> args = new ArrayList<>();
        StringBuffer sql = new StringBuffer("select lr.* from mtg_loan_request lr left join mtg_estate_eval_info eei on lr.estate_eval_id = eei.id " +
                "left join pb_user usr on lr.manager_id = usr.id left join pb_user usrTel on lr.tel_sale_manager = usrTel.id " +
                "left join mtg_channel ch on lr.channel_id = ch.id left join mtg_channel chNo on lr.channel_no = chNo.no where 1=1");

        if(BaseUtils.isNotBlank(searchParams, "EQ_status")) {
            sql.append(" AND lr.status = ?");
            args.add(searchParams.get("EQ_status"));
        }

        Channel channel = channelService.findByUserId(getCurrentUserId());
        if (!hasPermission(Constants.REQUEST_SEARCH_GLOBAL)) {
            sql.append(" AND (lr.manager_id in (SELECT user_id from mtg_channel where id=  '" + channel.getId() + "' or no like '" + channel.getNo() + "%') ");
            sql.append("or lr.channel_id in (SELECT id from mtg_channel where id=  '" + channel.getId() + "' or no like '" + channel.getNo() + "%')) ");
        }

        if(BaseUtils.isNotBlank(searchParams, "EQ_estateEvalInfo.propertyType")) {
            sql.append(" AND eei.property_type = ?");
            args.add(searchParams.get("EQ_estateEvalInfo.propertyType"));
        }

        if(BaseUtils.isNotBlank(searchParams, "LIKE_estateEvalInfo.houseAddress")) {
            sql.append(" AND eei.house_address like ?");
            args.add("%" + searchParams.get("LIKE_estateEvalInfo.houseAddress") + "%");
        }

        if(BaseUtils.isNotBlank(searchParams, "LIKE_user.realname")) {
            sql.append(" AND usr.realname like ?");
            args.add("%" + searchParams.get("LIKE_user.realname") + "%");
        }

        if(BaseUtils.isNotBlank(searchParams, "LIKE_channel.name")) {
            sql.append(" AND ch.name like ?");
            args.add("%" + searchParams.get("LIKE_channel.name") + "%");
        }

        if(BaseUtils.isNotBlank(searchParams, "LIKE_name")) {
            sql.append(" AND lr.name like ?");
            args.add("%" + searchParams.get("LIKE_name") + "%");
        }

        if(BaseUtils.isNotBlank(searchParams, "LIKE_mobile")) {
            sql.append(" AND lr.mobile like ?");
            args.add("%" + searchParams.get("LIKE_mobile") + "%");
        }

        if(BaseUtils.isNotBlank(searchParams, "GTE_createdAt")) {
            sql.append(" AND lr.created_at >= ?");
            args.add(String.valueOf(searchParams.get("GTE_createdAt")));
        }

        if(BaseUtils.isNotBlank(searchParams, "LTE_createdAt")) {
            sql.append(" AND lr.created_at <= ?");
            args.add(String.valueOf(searchParams.get("LTE_createdAt")));
        }

        if(BaseUtils.isNotBlank(searchParams, "LIKE_channelForNo.name")) {
            sql.append(" AND chNo.name like ?");
            args.add("%" + String.valueOf(searchParams.get("LIKE_channelForNo.name")) + "%");
        }

        if(BaseUtils.isNotBlank(searchParams, "LIKE_usrTel.realname")) {
            sql.append(" AND usrTel.realname like ?");
            args.add("%" + String.valueOf(searchParams.get("LIKE_usrTel.realname")) + "%");
        }

        sql.append(" order by lr.created_at desc ");

        PaginationHelper<LoanRequest> helper = new PaginationHelper<>();

        return helper.fetchPage(jdbcTemplate, sql.toString(), args.toArray(), pageBean, BeanPropertyRowMapper.newInstance(LoanRequest.class));
    }

    public List<LoanRequest> search(Map<String, Object> searchParams, Sort... sort) {
        return loanRequestDao.findAll(spec(searchParams), sort == null || sort.length == 0 ? new Sort(Direction.DESC, "createdAt") : sort[0]);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(String id) {
        loanRequestDao.delete(id);
    }

    public LoanRequest getOne(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return loanRequestDao.findOne(id);
    }

    public List<LoanRequest> findAll(List<String> idList) {
        return Lists.newArrayList(loanRequestDao.findAll(idList));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public LoanRequest save(LoanRequest loanRequest) {
        return loanRequestDao.save(loanRequest);
    }

    public List<LoanRequest> findByChannelId(String channelId) {
        return loanRequestDao.findByChannelId(channelId);
    }

    public Boolean exists(String channelId) {
        if (findByChannelId(channelId).isEmpty()) {
            return false;
        }
        return true;
    }

}


